package com.stock.filter;

import com.stock.util.JwtUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

public class JwtRequestFilter extends OncePerRequestFilter {

    private JwtUtil jwtUtil = new JwtUtil();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, javax.servlet.ServletException {
        String token = request.getHeader("token"); // 从请求头中获取 token
        if (token == null) {
            token = request.getParameter("token"); // 如果请求头没有 token，则尝试从 URL 参数中获取
        }
        String username = null;
        if (token != null) {
            // 提取用户名
            username = jwtUtil.extractUsername(token);
        }
        // 如果有 token 且用户未认证，验证 token 和用户名
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            if (jwtUtil.validateToken(token, username)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        username, null, new ArrayList<>());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } else {
                // Token 无效，抛出异常
                throw new RuntimeException("Invalid JWT token");
            }
        }
        // 继续执行过滤链
        chain.doFilter(request, response);
    }

}
